import request from '@/utils/request'

// 将文件转换为Base64
const fileToBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => {
      const base64Data = reader.result.split(',')[1]
      resolve(base64Data)
    }
    reader.onerror = error => reject(error)
  })
}

// 发送语音识别请求
export async function sendSpeechRecognition(audioBuffer) {
  try {
    const response = await fetch('/api/ai-chat/speech-recognition/', {
      method: 'POST',
      body: audioBuffer,
      headers: {
        'Content-Type': 'application/octet-stream'
      }
    })

    if (!response.ok) {
      const errorText = await response.text()
      throw new Error(`语音识别失败: ${errorText}`)
    }

    const result = await response.json()
    if (result.success && result.text) {
      return {
        success: true,
        text: result.text  // 直接返回文本内容
      }
    } else {
      throw new Error(result.error || '语音识别失败')
    }
  } catch (error) {
    console.error('语音识别请求失败:', error)
    throw error
  }
}

// 发送多模态消息
export async function sendMultiModalMessage(data) {
  let content = []
  
  // 处理文本消息
  if (data.text) {
    content.push({
      type: 'text',
      text: data.text
    })
  }
  
  // 处理图片
  if (data.image) {
    try {
      if (data.image.size > 5 * 1024 * 1024) { // 5MB限制
        throw new Error('图片大小不能超过5MB')
      }
      const base64Image = await fileToBase64(data.image)
      content.push({
        type: 'image_url',
        image_url: {
          url: `data:image/jpeg;base64,${base64Image}`
        }
      })
    } catch (error) {
      console.error('图片处理失败:', error)
      throw new Error(error.message || '图片处理失败')
    }
  }
  
  // 处理视频
  if (data.video) {
    try {
      if (data.video.size > 10 * 1024 * 1024) { // 10MB限制
        throw new Error('视频大小不能超过10MB')
      }
      const base64Video = await fileToBase64(data.video)
      content.push({
        type: 'video_url',
        video_url: {
          url: `data:;base64,${base64Video}`
        }
      })
    } catch (error) {
      console.error('视频处理失败:', error)
      throw new Error(error.message || '视频处理失败')
    }
  }

  // 确保历史消息的格式正确
  const formattedHistory = data.history?.map(msg => ({
    role: msg.role,
    content: Array.isArray(msg.content) 
      ? msg.content 
      : typeof msg.content === 'string'
        ? [{ type: 'text', text: msg.content }]
        : [{ type: 'text', text: msg.content.toString() }]
  })) || []

  const formattedData = {
    model: 'qwen-omni-turbo',
    messages: [
      {
        role: 'system',
        content: [{ 
          type: 'text', 
          text: '您是一个资深中医专家，具有丰富的中医理论知识和临床经验。' 
        }]
      },
      ...formattedHistory,
      {
        role: 'user',
        content
      }
    ],
    modalities: ['text'],
    stream: true,
    stream_options: {
      include_usage: true
    }
  }

  console.log('发送的数据:', JSON.stringify(formattedData, null, 2))

  const response = await fetch('/api/ai-chat/chat/', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(formattedData)
  })

  if (!response.ok) {
    const errorText = await response.text()
    console.error('请求失败:', errorText)
    throw new Error(`请求失败: ${errorText}`)
  }

  const reader = response.body.getReader()
  const decoder = new TextDecoder()
  
  return {
    async *[Symbol.asyncIterator]() {
      let buffer = ''
      
      try {
        while (true) {
          const { done, value } = await reader.read()
          if (done) break
          
          const chunk = decoder.decode(value, { stream: true })
          buffer += chunk
          
          const lines = buffer.split('\n')
          buffer = lines.pop() || ''  // 保留最后一个不完整的行
          
          for (const line of lines) {
            const trimmedLine = line.trim()
            if (trimmedLine.startsWith('data: ')) {
              const data = trimmedLine.slice(6)
              
              if (data === '[DONE]') {
                return
              }
              
              try {
                const parsedData = JSON.parse(data)
                if (parsedData.content) {
                  yield { content: parsedData.content }
                  // 强制立即刷新
                  await new Promise(resolve => setTimeout(resolve, 0))
                }
              } catch (e) {
                console.error('解析响应数据失败:', e)
              }
            }
          }
        }
      } finally {
        reader.releaseLock()
      }
    }
  }
} 